﻿
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;

namespace ZFY.UMC.BlazorWebAssembly
{
    public class IdentityApiHttpMessageHandler : DelegatingHandler
    {
        private readonly IAccessTokenProvider _accessTokenProvider;

        public IdentityApiHttpMessageHandler(IAccessTokenProvider accessTokenProvider)
        {
            _accessTokenProvider = accessTokenProvider;
        }

            protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                await SendBeforeAsync(request);

                var response = await base.SendAsync(request, cancellationToken);

                ReponseBeforeAsync(response);

                return response;
            }

            private void ReponseBeforeAsync(HttpResponseMessage response)
            {

                var contentType = response.Content.Headers.ContentType;
                if (string.IsNullOrEmpty(contentType.CharSet))
                {
                    contentType.CharSet = "utf-8";
                }

                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {

                }

            }

            private async Task SendBeforeAsync(HttpRequestMessage request)
            {
                Console.WriteLine("11111111");
                var tokenResult = await _accessTokenProvider.RequestAccessToken();

                if (tokenResult.TryGetToken(out var token))
                {
                    request.Headers.Add("Authorization", $"Bearer {token.Value}");
                
                }

            }
    }
}
